<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * sex
 * 获取男女
 * int $flag 1或者2
 * return 男 or 女
 */
if ( ! function_exists('sex'))
{
	function sex($flag)
	{
		if( empty($flag) ){
			return false;
		}
		if( 1==$flag ){
			return '男';
		}else {
			return '女';
		}
	}
}
/**
 * is_post
 * 是否为post
 * return true or false
 */
if ( ! function_exists('is_post'))
{
	function is_post()
	{
		return strtolower($_SERVER['REQUEST_METHOD']) == 'post';
	}
}
/**
 * ajax_return
 * ajax返回
 * array、str $data 随意信息
 * str $info 提示信息
 * int $status 0,1 1为成功
 * return json
 */
if ( ! function_exists('ajax_return'))
{
    function ajax_return($data='',$info='',$status=0)
    {
        //保证AJAX返回后也能保存日志
        $result  =  array();
        $result['status']  =  $status;
        $result['info'] =  $info;
        $result['data'] = $data;
        // 返回JSON数据格式到客户端 包含状态信息
        header("Content-Type:text/html; charset=utf-8");
        exit(json_encode($result));
    }
}
/**
 * format_num
 * 格式化数据
 * int $number 整数 eg:1234567
 * return 格式化后的数据 如 1,234,567
 */
if ( ! function_exists('format_num'))
{
	function format_num($number) {
		if ( $number == '' ) {
			return "-";
		}
		$nlen = strlen($number);
		while ( $nlen>3 ) {
			$fnumber = ",". substr($number,$nlen-3,3).$fnumber;
			$number = substr($number,0,-3);
			$nlen = strlen($number);
		}
		if ( $nlen <= 3 ) {
			$fnumber = $number.$fnumber;
		}
		return $fnumber;
	}
}
/**
 * bad_name
 * 屏蔽非法字符
 * str $str 错误提示
 * return array array('err'=>$str);
 */
if ( ! function_exists('bad_name'))
{
	function bad_name($name)
	{
		require_once(BASEPATH."plugins/badname_pi.php");
		foreach($badname as $key => $value)
		{
			if(strpos($name,$value)!==false) return false;
		}
		return true;
	}
}
/**
 * get_base
 * 获取变量表中的值
 * str $label 表示
 * return str
 */
if ( ! function_exists('get_base'))
{
	function get_base($label)
	{
		$CI =& get_instance();
		$CI->load->database();
		$sql_base = "select value from hd_base where label='{$label}'";
		//$row_base = S($sql_base);
        //if( empty($row_base) ){
        	$query_base = $CI->db->query($sql_base);
        	if( $query_base->num_rows()==0 ){
        		return '';
        	}
	        $row_base = $query_base->row();
			//S($sql_base,$row_base,86400*30);
        //}
        return $row_base->value;
	}
}
/**
 * get_date_time
 * 返回格式化的日期
 * int $time unix时间戳
 * return str
 */
if ( ! function_exists('get_date_time'))
{
	function get_date_time($time)
	{
		return 	date("Y-m-d H:i:s",$time);
	}
}
/**
 * dump
 * 格式化数组输出
 * int $time unix时间戳
 * return str
 */
if ( ! function_exists('dump'))
{
	function dump($var, $echo=true,$label=null, $strict=true)
	{
	    $label = ($label===null) ? '' : rtrim($label) . ' ';
	    if(!$strict) {
	        if (ini_get('html_errors')) {
	            $output = print_r($var, true);
	            $output = "<pre>".$label.htmlspecialchars($output,ENT_QUOTES)."</pre>";
	        } else {
	            $output = $label . " : " . print_r($var, true);
	        }
	    }else {
	        ob_start();
	        var_dump($var);
	        $output = ob_get_clean();
	        if(!extension_loaded('xdebug')) {
	            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
	            $output = '<pre>'. $label. htmlspecialchars($output, ENT_QUOTES). '</pre>';
	        }
	    }
	    if ($echo) {
	        echo($output);
	        return null;
	    }else
	        return $output;
	}
}
/**
 * display
 * 成功或者是错误提示页面
 * str $message 提示信息
 * str $url 要跳转到的url
 * int $status 1成功 2失败
 * return str
 */
if ( ! function_exists('display'))
{
	function display($message,$url,$status=1){
	 	if($status==1) {
            $data['wait_second'] = 1;
            $data['title'] = '操作成功!';
        }else{
            $data['wait_second'] = 3;
            $data['title'] = '操作失败!';
        }
        $data['jump_url'] = $url;
        $data['message'] = $message;
        $CI =& get_instance();
        $CI->load->view('public/success', $data);
        return true;
	 }
}
/**
 * get_query_info
 * 获取分页查询信息
 * array $get 查询参数
 * return obj $data
 */
if ( ! function_exists('get_query_info'))
{
	function get_query_info($get){
		$get = array_filter($get);
	 	$query_str ="";
		$i = 0;
		foreach ( $get as $k=>$v ){
			if( $k=='per_page'){
				continue;
			}
			if ( !empty($v) ){
				$query_str .= "{$k}={$v}";
				if ( $i>0 ){
					$query_str .= "&";
				}
			}
			$i++;
		}
		$data['query_str'] = $query_str;
		$data['per_page'] = $get['per_page'];
		unset($get['per_page']);
		$data['where'] = $get;
		return (object)$data;
	 }
}
/**
 * get_table_info
 * 获取某个表中某条记录的某个值
 * str $table 表名
 * str $field 字段名
 * array $where 条件
 */
if ( ! function_exists('get_table_info'))
{
	function get_table_info($table,$field,$where)
	{
		$CI =& get_instance();
		$CI->load->database();
		$CI->db->from($table)->select($field)->where($where);
		$query = $CI->db->get();
		if ($query->num_rows() > 0){
			$row = $query->row();
			return $row->$field;
		}else{
			return '';
		}
	}
}
/**
 * luck
 * 概率计算
 * float $dot 百分概率
 */
if ( ! function_exists('luck'))
{
	function luck($dot)
	{
		$dot = intval($dot);
		$dot = max($dot,0);//min dot = 0
		$dot = min($dot,100);//max dot = 100

		$one = rand(1,100);
		$total = range(1,100);
		$range = array();
		for($i=0; $i<$dot; $i++ ) {
			$range[] = $total[$i];
		}
		return in_array($one,$range);
	}
}
/**
 * auto_charset
 * str OR array $fContents 转换的字符串或者数组
 * str $from 起始编码
 * str $to 目标编码
 */
if ( ! function_exists('auto_charset'))
{
	function auto_charset($fContents,$from,$to){
	    $from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
	    $to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
	    if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
	        //如果编码相同或者非字符串标量则不转换
	        return $fContents;
	    }
	    if(is_string($fContents) ) {
	        if(function_exists('mb_convert_encoding')){
	            return mb_convert_encoding ($fContents, $to, $from);
	        }elseif(function_exists('iconv')){
	            return iconv($from,$to,$fContents);
	        }else{
	            return $fContents;
	        }
	    }
	    elseif(is_array($fContents)){
	        foreach ( $fContents as $key => $val ) {
	            $_key =     auto_charset($key,$from,$to);
	            $fContents[$_key] = auto_charset($val,$from,$to);
	            if($key != $_key )
	                unset($fContents[$key]);
	        }
	        return $fContents;
	    }
	    else{
	        return $fContents;
	    }
	}
}
/**
 * auto_charset
 * str OR array $fContents 转换的字符串或者数组
 * str $from 起始编码
 * str $to 目标编码
 */
if ( ! function_exists('is_utf8'))
{
	function is_utf8($string) {
	   return preg_match('%^(?:
	         [\x09\x0A\x0D\x20-\x7E]            # ASCII
	       | [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
	       |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
	       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
	       |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
	       |  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
	       | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
	       |  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
	   )*$%xs', $string);

	}
}
/**
 * memcache 使用
 */
if ( ! function_exists('S'))
{
	function S($key,$value='',$expire=86400)
	{
		$CI =& get_instance();
        $CI->load->library("MemcacheLibrary");
        if( !empty($value) ) {
        	return $CI->memcachelibrary->set($key,$value,$expire);
        }else{
        	return $CI->memcachelibrary->get($key);
        }
	}
}
/**
 * memcache 使用
 */
if ( ! function_exists('S_del'))
{
	function S_del($key)
	{
		$CI =& get_instance();
        $CI->load->library("MemcacheLibrary");
        return $CI->memcachelibrary->delete($key);
	}
}

/**
 * sql_where_in sql where条件中in条件格式化
 */
if ( ! function_exists('sql_where_in'))
{
	function sql_where_in($where_id)
	{
		$where = array();
		foreach( $where_id as $v ){
			$where[] = "'".$v."'";
		}
		return implode(",",$where);
	}
}
/**
 * 读取语言包
 */
if ( ! function_exists('L'))
{
	function L($key)
	{
		$CI =& get_instance();
        $CI->load->helper('language');
        return lang($key);
	}
}
/**
 * 保存键值打乱数组
 */
if ( ! function_exists('shuffle_assoc'))
{
	function shuffle_assoc($array)
	{
		if( count($array)<=1 ){
			return $array;
		}
		$randomized_keys = array_rand($array, count($array));
		foreach($randomized_keys as $current_key){
			$output[$current_key] = $array[$current_key];
		}
		return $output;
	}
}
/**
 * 对查询结果集进行排序
 */
if ( ! function_exists('list_sort_by')){
	function list_sort_by($list,$field, $sortby='asc') {
	   if(is_array($list)){
	       $refer = $resultSet = array();
	       foreach ($list as $i => $data)
	           $refer[$i] = &$data[$field];
	       switch ($sortby) {
	           case 'asc': // 正向排序
	                asort($refer);
	                break;
	           case 'desc':// 逆向排序
	                arsort($refer);
	                break;
	           case 'nat': // 自然排序
	                natcasesort($refer);
	                break;
	       }
	       foreach ( $refer as $key=> $val)
	           $resultSet[] = &$list[$key];
	       return $resultSet;
	   }
	   return false;
	}
}
if ( ! function_exists('luck_ext')){
	function luck_ext($num,$max_num=100){
		if( $num<=0 ){
			return false;
		}
		$rand = rand(0,$max_num);
		$num = $num*$max_num;
		if( $num>$max_num ){
			return true;
		}
		if( $rand<=$num ){
			return true;
		}
		return false;
	}
}
/**
 * get_role_name_by_id
 * 通过角色id获取角色名
 * int $id 表示
 * return str
 */
if ( ! function_exists('get_role_name_by_id'))
{
	function get_role_name_by_id($id)
	{
		$CI =& get_instance();
		$CI->load->database();
		$sql_role = "select id,sex,name,clv,school,feature,infamy,faction from hl_role where id={$id}";
		$row_role = S($sql_role);
        if( empty($row_role) ){
        	$query_role = $CI->db->query($sql_role);
        	if( $query_role->num_rows()==0 ){
        		return '';
        	}
	        $row_role = $query_role->row();
			S($sql_role,$row_role,60*10);
        }
        return $row_role;
	}
}
if ( ! function_exists('error_record'))
{
	function error_record($code,$message) {
		throw new Exception($message,$code);
	}
}
/*
 * 后台权限
 */
 if ( ! function_exists('power'))
{
     function power($id)
     {
		$CI =& get_instance();
		$query = $CI->db->from("admin")->where('id', $id)->get();
		$row_admin = $query->row();
		if ( $row_admin->type=='super' ){
			return true;
		}
		$requestUrl = $_SERVER['REQUEST_URI'];
		$aryUrl = explode("game/admin.php/",$requestUrl);
		$url = $aryUrl[1];
		if ( strpos($url,"/")!=false ){
			$aryUrl = explode("/",$url);
			$action = $aryUrl[0];
			$func = $aryUrl[1];
		}else{
			$action = $url;
		}
		if ( empty($func) ){
			$func = 'index';
		}
		$where = array('action_name'=>$action,'method_name'=>$func);
		$query = $CI->db->from("admin_power")->where($where)->get();
		$row = $query->row();
		if( !empty($row->id) ){
			echo '<script type="text/javascript" charset="utf-8">alert("没有权限");history.back();</script>';
		}
     }
}
/*
 *
 */
 if ( ! function_exists('location_replace'))
{
	function location_replace($msg='',$target='')
	{
		$msg = trim($msg);
		$target = trim($target);
		$str = '<script type="text/javascript" charset="utf-8">';
		if($msg) $str .= 'alert("'.$msg.'");';
		$str .= ($target ? $target.'.' : '').'history.back();';
		$str .= '</script>';
		echo $str;
		die;
	}
}
//通过身份证获取年龄以及是否满18岁 未满flag为1
function get_date_by_id_card($id_card){
     if(strlen($id_card) == 18){
          $tyear = intval(substr($id_card, 6, 4));
          $tmonth = intval(substr($id_card, 10, 2));
          $tday = intval(substr($id_card, 12, 2));
          if($tyear > date("Y") || $tyear < (date("Y")-100)){
               $flag = 0;
          }elseif($tmonth < 0 || $tmonth > 12){
               $flag = 0;
          }elseif($tday < 0 || $tday > 31){
               $flag = 0;
          }else{
               $tdate = $tyear . "-" . $tmonth . "-" . $tday;
               if((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60){
                    $flag = 0;
               }else{
                    $flag = 1;
               }
          }
     }elseif(strlen($id_card) == 15){
          $tyear = intval("19" . substr($id_card, 6, 2));
          $tmonth = intval(substr($id_card, 8, 2));
          $tday = intval(substr($id_card, 10, 2));
          if($tyear > date("Y") || $tyear < (date("Y")-100)){
               $flag = 0;
          }elseif($tmonth < 0 || $tmonth > 12){
               $flag = 0;
          }elseif($tday < 0 || $tday > 31){
               $flag = 0;
          }else{
               $tdate = $tyear . "-" . $tmonth . "-" . $tday;
               if((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60){
                    $flag = 0;
               }else{
                    $flag = 1;
               }
          }
     }
     return array(
          'flag'=>$flag,
          'date'=>$tdate,
     );
}
/**
 * 验证函数
 */
function regex($value,$rule) {
	$validate = array(
	    'require'=> '/.+/',
	    'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
	    'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
	    'currency' => '/^\d+(\.\d+)?$/',
	    'number' => '/^\d+$/',
	    'zip' => '/^[1-9]\d{5}$/',
	    'integer' => '/^[-\+]?\d+$/',
	    'double' => '/^[-\+]?\d+(\.\d+)?$/',
	    'english' => '/^[A-Za-z]+$/',
	);
	if(isset($validate[strtolower($rule)]))
        $rule   =   $validate[strtolower($rule)];
	return preg_match($rule,$value)===1;
}
/**
 * ajax_return
 * ajax返回
 * array、str $data 随意信息
 * str $info 提示信息
 * int $status 0,1 1为成功
 * return json
 */
if ( ! function_exists('ajax_return'))
{
    function ajax_return($data='',$info='',$status=0)
    {
        //保证AJAX返回后也能保存日志
        $result  =  array();
        $result['status']  =  $status;
        $result['info'] =  $info;
        $result['data'] = $data;
        // 返回JSON数据格式到客户端 包含状态信息
        header("Content-Type:text/html; charset=utf-8");
        exit(json_encode($result));
    }
}
if ( ! function_exists('error_return'))
{
    function error_return($info='',$data='')
    {
        ajax_return($data,$info,0);
    }
}
if ( ! function_exists('success_return'))
{
    function success_return($info='',$data='')
    {
        ajax_return($data,$info,1);
    }
}
/*
*gmail 发邮件
*$to str or array 收件人
*$subjert题目
*$body 邮件内容
*/
if ( ! function_exists('sendmail_by_phpmailer'))
{
	function sendmail_by_phpmailer($to,$subject,$body)
	{
		$config = array(
			//gmail设置
			'username'=>'zhe.tan.dodo@gmail.com', //邮箱
			'password'=>'12221008',//邮箱密码
			//发件人：fat001 <zhe.tan.dodo@gmail.com>
			'from'=>'zhe.tan.dodo@gmail.com',
			'fromname'=>'dodo',//发件人
			'host'=>'smtp.gmail.com',
		);
		require_once "./homepage/libraries/phpmailer/class.phpmailer.php";
		$mail= new PHPMailer(); //建立新物件
		$mail->IsSMTP(); //設定使用SMTP方式寄信
		$mail->SMTPAuth = true; //設定SMTP需要驗證
		$mail->SMTPSecure = "ssl"; // Gmail的SMTP主機需要使用SSL連線
		$mail->Host = $config['host']; //Gamil的SMTP主機
		$mail->Port = 465;  //Gamil的SMTP主機的SMTP埠位為465埠。
		$mail->CharSet = "utf-8"; //設定郵件編碼
		$mail->Username = $config['username']; //設定驗證帳號
		$mail->Password = $config['password']; //設定驗證密碼
		$mail->From = $config['from']; //設定寄件者信箱
		$mail->FromName = $config['fromname']; //設定寄件者姓名
		$mail->Subject  = "=?UTF-8?B?".base64_encode($subject)."?=";
		$mail->Body = $body; //設定郵件內容
		$mail->IsHTML(true); //設定郵件內容為HTML
		if ( !is_array($to) ){
			$mail->AddAddress($to); //設定收件者郵件及名稱
			if(!$mail->Send()) {
				//echo "Mailer Error: " . $mail->ErrorInfo;
				return false;
			} else {
				return true;
			}
		} else {
			foreach ( $to as $user ){
				$mail->AddAddress($user); //設定收件者郵件及名稱
				if(!$mail->Send()) {
					//echo "Mailer Error: " . $mail->ErrorInfo;
					return false;
				} else {
					return true;
				}
			}
		}
	}
}
/**
 * public_img_path
 * 公共图片路径
 */
if ( ! function_exists('public_img_path'))
{
	function public_img_path()
	{
		return base_url().'public/_img/';
	}
}
/**
 * public_css_path
 * 公共css路径
 */
if ( ! function_exists('public_css_path'))
{
	function public_css_path()
	{
		return base_url().'public/_css/';
	}
}
/**
 * public_js_path
 * 公共js路径
 */
if ( ! function_exists('public_js_path'))
{
	function public_js_path()
	{
		return base_url().'public/_js/';
	}
}
/* End of file array_helper.php */
/* Location: ./system/helpers/mine_helper.php */